<?php
declare (strict_types=1);

namespace app\platform\controller;

use think\facade\View;
use think\response\Json;

class Website extends PlatformBase
{
    public function index()
    {
        $merchantUserObj = new \app\platform\business\Merchant();
        $merchant        = $merchantUserObj->getMerchantUserFromSession();
        if (isset($merchant['enterprise_id']) && $merchant['enterprise_id'] != 0) {
            return redirect((string)url('website/lists'));
        }

        $merchantBusiness = new \app\platform\business\Enterprise();
        $enterprises      = $merchantBusiness->getAllEnterprise();

        $rows    = [];
        $rows[0] = ['id' => 0, 'title' => '全部', 'children' => [], 'spread' => true];
        foreach ($enterprises as $key => $enterprise) {
            $rows[0]['children'][] = ['id' => $enterprise['id'], 'title' => $enterprise['name'], 'children' => [], 'pid' => 0];
        }
        View::assign(['enterprises' => json_encode($rows, JSON_UNESCAPED_UNICODE)]);

        return View::fetch();
    }

    public function lists(): string
    {
        $list            = $this->request->param('list', 0, 'intval');
        $enterpriseId    = $this->request->param('enterprise_id', 0, 'intval');
        $merchantUserObj = new \app\platform\business\Merchant();
        $merchant        = $merchantUserObj->getMerchantUserFromSession();

        View::assign(['enterprise_id' => $enterpriseId, 'merchant' => $merchant, 'list' => $list]);

        return View::fetch();
    }

    public function list(): Json
    {
        $page             = $this->request->param('page', 1, 'intval');
        $limit            = $this->request->param('limit', 10, 'intval');
        $name             = $this->request->param('name', '', 'trim');
        $status           = $this->request->param('status', 0, 'intval');
        $enterpriseId     = $this->request->param('enterprise_id', 0, 'intval');
        $websiteBusiness  = new \app\platform\business\Website();
        $merchantBusiness = new \app\platform\business\Merchant();
        $merchant         = $merchantBusiness->getMerchantUserFromSession();

        $where = [];
        if ($name) {
            $where[] = ['name', 'like', '%' . $name . '%'];
        }
        if ($status) {
            $where[] = ['status', '=', $status];
        }
        if ($enterpriseId) {
            $where[] = ['enterprise_id', '=', $enterpriseId];
        }
        if (!$enterpriseId && $merchant['enterprise_id']) {
            $where[] = ['enterprise_id', '=', $merchant['enterprise_id']];
        }

        $websiteInfo = $websiteBusiness->getWebsiteList($page, $limit, $where);
        return showList(config(self::_CONFIG_STATUS_SUCCESS_CODE), 'success', $websiteInfo['rows'], $websiteInfo['count']);
    }

    public function add(): string
    {
        $enterpriseId       = $this->request->param('enterprise_id', 0, 'intval');
        $enterpriseBusiness = new \app\platform\business\Enterprise();
        $enterprise         = $enterpriseBusiness->findEnterpriseById($enterpriseId);

        View::assign([
            'enterprise_id'   => $enterpriseId,
            'enterprise_name' => $enterprise['name'],
            'app_id'          => getRandomStr(30),
            'app_secret'      => getRandomStr(30),
            'app_jwt_secret'  => getRandomStr(30),
        ]);

        return View::fetch();
    }

    public function doAdd(): Json
    {
        if (!$this->request->isPost()) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), self::_REQUEST_WAY_ERROR_MESSAGE);
        }

        $name         = $this->request->param('name', '', 'trim');
        $code         = $this->request->param('code', '', 'trim');
        $dbHost       = $this->request->param('db_host', '', 'trim');
        $dbUser       = $this->request->param('db_user', '', 'trim');
        $dbName       = $this->request->param('db_name', '', 'trim');
        $dbPrefix     = $this->request->param('db_prefix', '', 'trim');
        $dbPassword   = $this->request->param('db_password', '', 'trim');
        $dbPort       = $this->request->param('db_port', 0, 'intval');
        $domain       = $this->request->param('domain', '', 'trim');
        $cdnBucket    = $this->request->param('cdn_bucket', '', 'trim');
        $cdnDomain    = $this->request->param('cdn_domain', '', 'trim');
        $enterpriseId = $this->request->param('enterprise_id', 0, 'intval');
        $appId        = $this->request->param('app_id', '', 'trim');
        $appSecret    = $this->request->param('app_secret', '', 'trim');
        $appJwtSecret = $this->request->param('app_jwt_secret', '', 'trim');
        $frontendUrl  = $this->request->param('frontend_url', '', 'trim');
        $backendUrl   = $this->request->param('backend_url', '', 'trim');
        $websiteType  = $this->request->param('website_type', 0, 'intval');
        $status       = $this->request->param('status', 0, 'intval');

        $data     = [
            'name'           => $name,
            'code'           => $code,
            'db_host'        => $dbHost,
            'db_user'        => $dbUser,
            'db_name'        => $dbName,
            'db_prefix'      => $dbPrefix,
            'db_password'    => $dbPassword,
            'db_port'        => $dbPort,
            'domain'         => $domain,
            'cdn_bucket'     => $cdnBucket,
            'cdn_domain'     => $cdnDomain,
            'enterprise_id'  => $enterpriseId,
            'app_id'         => $appId,
            'app_secret'     => $appSecret,
            'app_jwt_secret' => $appJwtSecret,
            'frontend_url'   => $frontendUrl,
            'backend_url'    => $backendUrl,
            'website_type'   => $websiteType,
            'status'         => $status == self::_IS_ENABLE_STATUS ? self::_IS_ENABLE_STATUS : self::_IS_DISABLE_STATUS,
        ];
        $validate = (new \app\platform\validate\Website())->scene('add');
        if (!$validate->check($data)) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), $validate->getError());
        }

        $websiteBusiness = new \app\platform\business\Website();
        $res             = $websiteBusiness->addWebsite($data);
        if ($res[self::_RESULT]) {
            return show(config(self::_CONFIG_STATUS_SUCCESS_CODE), $res[self::_MESSAGE]);
        }

        return show(config(self::_CONFIG_STATUS_ERROR_CODE), $res[self::_MESSAGE]);
    }

    public function edit(): string
    {
        $id = $this->request->param('id', 0, 'intval');
        if (!$id) {
            View::assign(['msg' => self::_PARAMETER_ERROR_MESSAGE]);
            return View::fetch('permission/msg');
        }

        $websiteBusiness = new \app\platform\business\Website();
        $website         = $websiteBusiness->findWebsiteById($id);
        if (empty($website)) {
            View::assign(['msg' => self::_PARAMETER_ERROR_MESSAGE]);
            return View::fetch('permission/msg');
        }

        $enterpriseBusiness = new \app\platform\business\Enterprise();
        $enterprise         = $enterpriseBusiness->findEnterpriseById($website['enterprise_id']);

        View::assign(["website" => $website, 'enterprise_name' => $enterprise['name']]);

        return View::fetch();
    }

    public function doEdit(): Json
    {
        if (!$this->request->isPost()) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), self::_REQUEST_WAY_ERROR_MESSAGE);
        }

        $id           = $this->request->param('id', 0, 'intval');
        $name         = $this->request->param('name', '', 'trim');
        $dbHost       = $this->request->param('db_host', '', 'trim');
        $dbUser       = $this->request->param('db_user', '', 'trim');
        $dbName       = $this->request->param('db_name', '', 'trim');
        $dbPrefix     = $this->request->param('db_prefix', '', 'trim');
        $dbPassword   = $this->request->param('db_password', '', 'trim');
        $dbPort       = $this->request->param('db_port', 0, 'intval');
        $domain       = $this->request->param('domain', '', 'trim');
        $cdnBucket    = $this->request->param('cdn_bucket', '', 'trim');
        $cdnDomain    = $this->request->param('cdn_domain', '', 'trim');
        $enterpriseId = $this->request->param('enterprise_id', 0, 'intval');
        $appId        = $this->request->param('app_id', '', 'trim');
        $appSecret    = $this->request->param('app_secret', '', 'trim');
        $appJwtSecret = $this->request->param('app_jwt_secret', '', 'trim');
        $frontendUrl  = $this->request->param('frontend_url', '', 'trim');
        $backendUrl   = $this->request->param('backend_url', '', 'trim');
        $websiteType  = $this->request->param('website_type', 0, 'intval');
        $status       = $this->request->param('status', 0, 'intval');

        $data     = [
            'name'           => $name,
            'db_host'        => $dbHost,
            'db_user'        => $dbUser,
            'db_name'        => $dbName,
            'db_prefix'      => $dbPrefix,
            'db_password'    => $dbPassword,
            'db_port'        => $dbPort,
            'domain'         => $domain,
            'cdn_bucket'     => $cdnBucket,
            'cdn_domain'     => $cdnDomain,
            'enterprise_id'  => $enterpriseId,
            'app_id'         => $appId,
            'app_secret'     => $appSecret,
            'app_jwt_secret' => $appJwtSecret,
            'frontend_url'   => $frontendUrl,
            'backend_url'    => $backendUrl,
            'website_type'   => $websiteType,
            'status'         => $status == self::_IS_ENABLE_STATUS ? self::_IS_ENABLE_STATUS : self::_IS_DISABLE_STATUS,
        ];
        $validate = (new \app\platform\validate\Website())->scene('edit');
        if (!$validate->check($data)) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), $validate->getError());
        }

        $websiteBusiness = new \app\platform\business\Website();
        $res             = $websiteBusiness->updateWebsite($id, $data);
        if ($res[self::_RESULT]) {
            return show(config(self::_CONFIG_STATUS_SUCCESS_CODE), $res[self::_MESSAGE]);
        }

        return show(config(self::_CONFIG_STATUS_ERROR_CODE), $res[self::_MESSAGE]);
    }


    public function doDelete(): Json
    {
        if (!$this->request->isPost()) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), self::_REQUEST_WAY_ERROR_MESSAGE);
        }

        $id = $this->request->param('id', 0, 'intval');
        if (!$id) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), self::_PARAMETER_ERROR_MESSAGE);
        }

        $websiteBusiness = new \app\platform\business\Website();
        $res             = $websiteBusiness->deleteWebsite($id);
        if ($res[self::_RESULT]) {
            return show(config(self::_CONFIG_STATUS_SUCCESS_CODE), $res[self::_MESSAGE]);
        }

        return show(config(self::_CONFIG_STATUS_ERROR_CODE), $res[self::_MESSAGE]);
    }

    public function executeInitSql()
    {
        if (!$this->request->isPost()) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), self::_REQUEST_WAY_ERROR_MESSAGE);
        }

        $id = $this->request->param('id', 0, 'intval');
        if (!$id) {
            return show(config(self::_CONFIG_STATUS_ERROR_CODE), self::_PARAMETER_ERROR_MESSAGE);
        }

        $websiteBusiness = new \app\platform\business\Website();
        $res             = $websiteBusiness->executeInitSql($id);
        if ($res[self::_RESULT]) {
            return show(config(self::_CONFIG_STATUS_SUCCESS_CODE), $res[self::_MESSAGE]);
        }

        return show(config(self::_CONFIG_STATUS_ERROR_CODE), $res[self::_MESSAGE]);
    }
}
